-- 文件：scripts/prefabs/bboy_zhongyuan_blueprint.lua
-- 单外观的自定义蓝图，支持白名单、随机/指定两种生成方式，持久化保存可学习配方

local assets =
{
    Asset("ANIM", "anim/bboy_blueprint.zip"), -- 你的自定义动画资源
    -- 如需自定义物品栏图标：Asset("INV_IMAGE", "bboy_zhongyuan_blueprint"),
}

----------------------------------------------------------------
-- ✅ 工具函数：验证 recipe 是否可用（尽量宽松，重点是确保存在）
----------------------------------------------------------------
local function IsRecipeTeachOK(name)
    if type(name) ~= "string" then
        return false
    end
    local r = GetValidRecipe(name)
    if r == nil then
        return false
    end
    -- 不做过度限制：不检查 nounlock / builder_tag（你要的就是“指向性学习”）
    return true
end

local function PickRandomAllowedRecipe(allowed_recipes)
    local pool = {}
    for _, name in ipairs(allowed_recipes) do
        if IsRecipeTeachOK(name) then
            table.insert(pool, name)
        end
    end
    if #pool == 0 then
        return nil
    end
    return pool[math.random(#pool)]
end

----------------------------------------------------------------
-- ✅ 组件回调 / 持久化
----------------------------------------------------------------
local function onsave(inst, data)
    data.recipetouse = inst.recipetouse
end

local function onload(inst, data)
    -- 载入后仍保持原本指定的配方
    if data ~= nil and data.recipetouse ~= nil and IsRecipeTeachOK(data.recipetouse) then
        inst.recipetouse = data.recipetouse
    end
    -- 若存档里没有（理论上不会），则维持现状
    if inst.components.teacher ~= nil then
        inst.components.teacher:SetRecipe(inst.recipetouse or "unknown")
    end

    -- 重新设置名字
    local up = inst.recipetouse and string.upper(inst.recipetouse) or nil
    local itemname = (up and STRINGS.NAMES[up]) or STRINGS.NAMES.UNKNOWN or "UNKNOWN"
    inst.components.named:SetName(itemname .. " " .. (STRINGS.NAMES.BBOY_ZHONGYUAN_BLUEPRINT or "Blueprint"))
end

local function OnTeach(inst, learner)
    learner:PushEvent("learnrecipe", { teacher = inst, recipe = inst.components.teacher.recipe })
end

----------------------------------------------------------------
-- ✅ 外观/通用 fn
----------------------------------------------------------------
local function make_blueprint_base(specific_recipe_name, anim, prefab_name, allowed_recipes) -- specific_recipe_name 可为 nil（随机）
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddAnimState()
    inst.entity:AddNetwork()

    MakeInventoryPhysics(inst)

    -- 你的单一外观
    inst.AnimState:SetBank("bboy_blueprint")
    inst.AnimState:SetBuild("bboy_blueprint")
    inst.AnimState:PlayAnimation(anim)

    inst:SetPrefabName(prefab_name)

    MakeInventoryFloatable(inst, "med", nil, 0.75)

    inst.entity:SetPristine()
    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("inspectable")

    inst:AddComponent("inventoryitem")

    inst:AddComponent("erasablepaper")

    inst:AddComponent("named")

    inst:AddComponent("teacher")
    inst.components.teacher.onteach = OnTeach

    -- 燃料/可燃（和官方一致）
    inst:AddComponent("fuel")
    inst.components.fuel.fuelvalue = TUNING.SMALL_FUEL
    MakeSmallBurnable(inst, TUNING.SMALL_BURNTIME)
    MakeSmallPropagator(inst)

    MakeHauntableLaunch(inst)

    -- ✅ 决定教授的配方：指定 / 随机
    local target = nil
    if specific_recipe_name ~= nil then
        target = IsRecipeTeachOK(specific_recipe_name) and specific_recipe_name or nil
    end
    if target == nil then
        target = PickRandomAllowedRecipe(allowed_recipes)
    end
    inst.recipetouse = target or "unknown"
    inst.components.teacher:SetRecipe(inst.recipetouse)

    -- 命名
    local up = inst.recipetouse and string.upper(inst.recipetouse) or nil
    local up_name = prefab_name and string.upper(prefab_name) or nil
    local itemname = (up and STRINGS.NAMES[up]) or STRINGS.NAMES.UNKNOWN or "UNKNOWN"
    inst.components.named:SetName(itemname .. " " .. (up_name and STRINGS.NAMES[up_name] or "Blueprint"))

    inst.OnSave = onsave
    inst.OnLoad = onload

    return inst
end

----------------------------------------------------------------
-- ✅ 可学习的白名单（你可以随时增删，自动兼容）
----------------------------------------------------------------
local ALLOWED_RECIPES_ZHONGYUAN = {
    "wall_bboy_nether_blossom_item",
    "bboy_dry_well",
    "bboy_forsaken_grave",
    "bboy_paper_beefalo_item",
    "bboy_paper_effigy_item",
}

local ALLOWED_RECIPES_JIA = {
    "bboy_river_lantern",
    "bboy_candle_item",
    "bboy_candle_lamp",
    "wall_bboy_courtyard_item",
}

----------------------------------------------------------------
-- ✅ Prefab 构造器
--   1) 默认：SpawnPrefab("bboy_zhongyuan_blueprint") → 随机从白名单选一个
--   2) 指定：SpawnPrefab("<item>_bboy_zhongyuan_blueprint") → 指向性蓝图
----------------------------------------------------------------

-- 默认（随机）蓝图
local function MakeAnyZhongyuanBlueprint()
    return make_blueprint_base(nil, "zhongyuan", "bboy_zhongyuan_blueprint", ALLOWED_RECIPES_ZHONGYUAN)
end

local function MakeAnyJiaBlueprint()
    return make_blueprint_base(nil, "jia", "bboy_jia_blueprint", ALLOWED_RECIPES_JIA)
end

-- 指定蓝图工厂
local function MakeSpecificZhongyuanBlueprint(itemname)
    return function()
        return make_blueprint_base(itemname, "zhongyuan", "bboy_zhongyuan_blueprint", ALLOWED_RECIPES_ZHONGYUAN)
    end
end

local function MakeSpecificJiaBlueprint(itemname)
    return function()
        return make_blueprint_base(itemname, "jia", "bboy_jia_blueprint", ALLOWED_RECIPES_JIA)
    end
end

----------------------------------------------------------------
-- ✅ 注册所有 Prefab
----------------------------------------------------------------
local prefabs = {}

-- 1) 默认（随机）蓝图
table.insert(prefabs, Prefab("bboy_zhongyuan_blueprint", MakeAnyZhongyuanBlueprint, assets))

table.insert(prefabs, Prefab("bboy_jia_blueprint", MakeAnyJiaBlueprint, assets))

-- 2) 为白名单中的每个物品自动注册
for _, name in ipairs(ALLOWED_RECIPES_ZHONGYUAN) do
    local prefabname = string.lower(name .. "_bboy_zhongyuan_blueprint")
    table.insert(prefabs, Prefab(prefabname, MakeSpecificZhongyuanBlueprint(name), assets))
end

for _, name in ipairs(ALLOWED_RECIPES_JIA) do
    local prefabname = string.lower(name .. "_bboy_jia_blueprint")
    table.insert(prefabs, Prefab(prefabname, MakeSpecificJiaBlueprint(name), assets))
end

return unpack(prefabs)
